package wsdc.app.main.v1;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.io.File;

//  生成证书的api
@Component
@Slf4j
public class CertApi {
    @Autowired
    CertificateService service;
    @Autowired
            CertConfig certConfig;
    String fileRoot = "D:\\cert\\certs";

    @EventListener(classes = ApplicationReadyEvent.class)
    public void test(){
        fileRoot = certConfig.getDir();
       // wildSsl("uni.wsdchigh.top");
        //createCa4();
        if(false){
            try{
                CertificateService.PKCS12Bundle cp = service.loadFromPKCS12("d:/cert/certs/a1.p12", "certpass123");
                service.saveCertificateAsPEM(cp.getCertificate(), "ca-cert.pem");
                service.savePrivateKeyAsPEM(cp.getPrivateKey(),"ca-key.pem");
                int k= 0;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    //  创建根证书
    public void createCa() {
        try {
            File file = new File(fileRoot, "ca-key.pem");
            if (file.exists()) {
                log.info("ca-key.pem已存在,请删除后再试");
                return;
            }
            CertificateService.CertificateBundle caBundle = service.createCa("My CA", "My Organization", "CN", 10);

            // 保存为文件
            service.saveCertificateAsPEM(caBundle.getCertificate(), "ca-cert.pem");
            service.savePrivateKeyAsPEM(caBundle.getPrivateKey(), "ca-key.pem");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //  创建泛域名证书
    public void wildSsl(String hostname) {
        String fileDir = toWildcardDomain(hostname);
        //  去掉开始的 *. 不然无法创建文件夹
        fileDir = fileDir.substring(2);
        File f1 = new File(fileRoot, fileDir);
        //  创建文件夹 防止不存在报错
        if(!f1.exists()){
            f1.mkdir();
        }else {
            //  已经存在就不要继续创建
            return ;
        }
        try {
            String password = "certpass123";
            CertificateService.CertificateBundle caBundle = caBundle();
            CertificateService.CertificateBundle sslBundle = service.createSslWild(caBundle, "*." + hostname, "My Organization", "CN",
                    new String[]{hostname,fileDir}, hostname, 1, password);

            // 保存为PKCS12格式文件（Tomcat可以直接使用）
            service.saveAsPKCS12WithChain(sslBundle.getCertificate(), sslBundle.getPrivateKey(),caBundle.getCertificate(), fileDir+"/"+"tomcat-ssl.p12", password);

            //  保存原始数据
            service.savePrivateKeyAsPEM(sslBundle.getPrivateKey(), fileDir+"/"+"tomcat-ssl.key");
            service.saveCertificateAsPEM(sslBundle.getCertificate(), fileDir+"/"+"tomcat-ssl.crt");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //  生成单证书
    public void singleSsl(String hostname) {
        String fileDir = hostname;
        File f1 = new File(fileRoot, fileDir);
        //  创建文件夹 防止不存在报错
        if(!f1.exists()){
            f1.mkdir();
        }else {
            //  已经存在就不要继续创建
            return ;
        }
        try {
            String password = "certpass123";
            CertificateService.CertificateBundle caBundle = caBundle();
            CertificateService.CertificateBundle sslBundle = service.createSsl(caBundle, "*." + hostname, "My Organization", "CN",
                    new String[]{hostname,fileDir}, 1);

            // 保存为PKCS12格式文件（Tomcat可以直接使用）
            service.saveAsPKCS12WithChain(sslBundle.getCertificate(), sslBundle.getPrivateKey(),caBundle.getCertificate(), fileDir+"/"+"tomcat-ssl.p12", password);

            //  保存原始数据
            service.savePrivateKeyAsPEM(sslBundle.getPrivateKey(), fileDir+"/"+"tomcat-ssl.key");
            service.saveCertificateAsPEM(sslBundle.getCertificate(), fileDir+"/"+"tomcat-ssl.crt");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String toWildcardDomain(String domain) {
        if (domain == null || domain.isEmpty()) {
            return domain;
        }

        // 如果已经包含通配符，则直接返回
        if (domain.startsWith("*.")) {
            return domain;
        }

        // 分割域名各部分
        String[] parts = domain.split("\\.");

        // 如果只有一部分，直接添加*.
        if (parts.length == 1) {
            return "*." + domain;
        }

        // 如果只有两部分，直接将第一部分替换为*
        if (parts.length == 2) {
            return "*." + parts[1];
        }

        // 3
        if (parts.length == 3) {
            return "*." + parts[parts.length - 2] + "." + parts[parts.length - 1];
        }

        //  少部分情况有4段
        if (parts.length == 4) {
            return "*." + parts[parts.length - 3] + "." + parts[parts.length - 2] + "." + parts[parts.length - 1];
        }

        return domain;
    }

    private CertificateService.CertificateBundle caBundle() throws Exception {
        File certFile = new File("d:/cert/certs/ca-cert.pem");
        File keyFile = new File("d:/cert/certs/ca-key.pem");

        // 如果文件存在，则从文件加载CA证书
        if (certFile.exists() && keyFile.exists()) {
            return service.loadCACertificateFromDisk("d:/cert/certs/ca-cert.pem", "d:/cert/certs/ca-key.pem");
        }

        return null;
    }
}
